import configparser
import time
from functools import wraps
import sys

quit_text = 'q'

def display_exit():
    print(f"(type '{quit_text}' to exit the program.)")

def text2exit(func):
    def wrapper(*args, **kwargs):
        text = kwargs.get('quit_text', quit_text)
        result = func(*args, **kwargs)
        if str(result).lower() == text:
            sys.exit()
        return result
    return wrapper

def read_config_value(config_file, section, key):
    config = configparser.ConfigParser()
    config.read(config_file)

    # 检查配置文件中是否存在指定的section和key
    if config.has_section(section) and config.has_option(section, key):
        return config.get(section, key)
    else:
        return None


def rate_limited(max_calls=3, time_window=60):
    def decorator(func):
        calls = 0
        last_reset = time.time()

        @wraps(func)
        def wrapper(*args, **kwargs):
            nonlocal calls, last_reset

            # 如果当前时间与上一次重置的时间超过时间窗口，重置调用计数
            if time.time() - last_reset > time_window:
                calls = 0
                last_reset = time.time()

            # 如果调用计数未达到上限，调用函数并递增调用计数
            if calls < max_calls:
                result = func(*args, **kwargs)
                calls += 1
                return result
            else:
                # 达到调用上限
                remaining_time = time_window - (time.time() - last_reset)
                print(f"一分钟最多调用3次，等待 {remaining_time:.2f} 秒后重新执行...\n", end="", flush=True)
                
                # 实时显示剩余等待时间
                while remaining_time > 0:
                    print(f"\r剩余等待时间：{remaining_time:.2f} 秒", end="", flush=True)
                    time.sleep(1)
                    remaining_time -= 1

                print("\n重新执行函数...\n")
                calls = 0
                last_reset = time.time()

                # 重新调用函数
                return func(*args, **kwargs)

        return wrapper

    return decorator

